/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nl.rainbowsheep.reisorg.rest.service.service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.rainbowsheep.reisorg.rest.service.model.Country;
import nl.rainbowsheep.reisorg.rest.service.model.CountryLocalized;
import nl.rainbowsheep.reisorg.rest.service.model.Language;
import nl.rainbowsheep.reisorg.rest.service.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Service class for Country where business logic is placed
 */
@Service
public class CountryService {

    @Autowired
    private CountryRepository countryRepository;
    @Autowired
    private LanguageService langService;

    public List<Country> getAllCountries() {
        return countryRepository.findAll();
    }

    public Country getCountryById(long id) {
        return countryRepository.findOne(id);
    }
    
    public Country getCountryByName(String name) {
        return countryRepository.findByName(name);
    }

    public Country save(Country country) {
        Country countryToCheck = getCountryByName(country.getName());
        Map<Language, CountryLocalized> localizedMap = null;
        
        if (countryToCheck != null) {
            country.setId(countryToCheck.getId());
            if (countryToCheck.getLocale() != null) {
                localizedMap = countryToCheck.getLocale();
            }
        }
        if (localizedMap == null) {
            localizedMap = new HashMap<Language, CountryLocalized>();
        }
        country.setLocale(localizedMap);
        Date currentDate = new Date();
        country.setLastUpdate(new Timestamp(currentDate.getTime()));
        return countryRepository.save(country);
    }
}
